package com.bianmaba.beans.datamanagement;

import com.bianmaba.dc.bean.CollectionData;
import com.bianmaba.dc.bean.DataType;
import com.bianmaba.spring.data.jpa.domain.annotations.QueryCacheable;
import com.bianmaba.spring.data.jpa.domain.entity.UuidIdentityEntity;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Entity
@DynamicUpdate()
@DynamicInsert()
//此注解重新定义为是否开始查询缓存
@QueryCacheable
//此注解表示此类支持二级缓存，缓存名称为：defaultEntityCache
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@Data
@NoArgsConstructor
@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"projectId", "interfaceType", "dataType"})})
public class DataTable extends UuidIdentityEntity {
    private String projectId;
    private String interfaceType;
    private String dataType;
    private String taskId;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinTable(name = "data_table_ref_data_row", joinColumns = {@JoinColumn(name = "data_table_id")}, inverseJoinColumns = {@JoinColumn(name = "data_row_id")})
    private List<DataRow> rows = new ArrayList<>(0);

    public static DataTable of(String projectId, String interfaceType, String taskId, String dataType, List<CollectionData.Row> rows) {
        DataTable table = new DataTable();
        table.setProjectId(projectId);
        table.setInterfaceType(interfaceType);
        table.setDataType(dataType);
        table.setTaskId(taskId);
        table.setRows(new ArrayList<>(0));
        for (CollectionData.Row row : rows) {
            List<DataItem> items = new ArrayList<>();
            Set<Map.Entry<String, Object>> entries = row.getDatas().entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                DataItem item = new DataItem();
                item.setProperty(entry.getKey());
                String value = entry.getValue() != null && StringUtils.isNotEmpty(entry.toString()) ? entry.getValue().toString() : null;
                item.setValue(value);
                items.add(item);
            }
            if (DataType.SOURCE_DATA.equalsIgnoreCase(dataType)) {
                DataRow dataRow = DataRow.of(items);
                table.getRows().add(dataRow);
            } else {
                DataRow dataRow = DataRow.of(row.getStartDate(), row.getEndDate(), items);
                table.getRows().add(dataRow);
            }
        }
        return table;
    }
}
